﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public class ImageAnimation:MonoBehaviour
{
	public List<Sprite> spriteList;
	public float fps;
	public bool loop;
	private int frameIndex = 0;
	private uint timerId;
	public bool playOnAwake = true;
	private Image image;
	void Awake()
	{
		image = GetComponent<Image>();
		if(playOnAwake)
		{
			Play();
		}
	}
	// Use this for initialization
	void Start()
	{

	}

	public void OnDisable()
	{
	}

	public void OnEnable()
	{

	}

	public void OnDestroy()
	{
		UTimer.Remove(timerId);
	}

	[ContextMenu("Play")]
	public void Play()
	{
		if(image == null)
		{
			return;
		}
		UTimer.Remove(timerId);
		float oneFrameTime = 1 / fps;
		frameIndex = 0;
		int rumTimes = loop ? int.MaxValue : spriteList.Count;
		timerId = UTimer.AddTimerRepeat(oneFrameTime,rumTimes,() =>
		{
			frameIndex %= spriteList.Count;
			image.sprite = spriteList[frameIndex];
			frameIndex++;
		});
	}
}
